package com.gxa.component.aspect;

import com.gxa.annotation.Perm;
import com.gxa.component.cache.LocalCache;
import com.gxa.exception.GlobalException;
import com.gxa.mapper.system.PermMapper;
import com.gxa.pojo.entity.system.User;
import com.gxa.utils.Constants;
import com.gxa.utils.MessageCode;
import com.gxa.utils.UserThreadLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @Author lch
 * @Date 2024/2/22 15:32
 * @Description 权限切面
 **/
@Component
@Aspect
public class PermAspect {

    @Resource
    private PermMapper permMapper;

    @Resource
    private LocalCache localCache;

    @Around("@annotation(com.gxa.annotation.Perm)")
    public Object access(ProceedingJoinPoint joinPoint) {
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        Perm permAnnotation = method.getAnnotation(Perm.class);
        if (permAnnotation != null) {
            //取出权限注解中的值
            String permValue = permAnnotation.value();
            User user = UserThreadLocal.getUser();
            //1.先从本地缓存中获取权限
            Set<String> permSet = (Set<String>) localCache.get(Constants.LOCAL_CACHE_PREFIX + user.getId());

            if (permSet == null) {
                //2.本地缓存未命中，从数据库中查询权限
                permSet = this.permMapper.queryPermsByUserId(user.getId());
                if (permSet != null) {
                    //把从数据库查到的权限信息保存到本地缓存中
                    localCache.setLocalCache(Constants.LOCAL_CACHE_PREFIX + user.getId(), permSet);
                }
            }

            //再次检查是找到权限
            if (permSet == null) {
                throw new GlobalException(MessageCode.NO_PERMISSION);
            }

            //判断用户是否有权限进行该操作
            boolean flag = permSet.contains(permValue);
            if (!flag) {
                //没有权限
                throw new GlobalException(MessageCode.NO_PERMISSION);
            }
        }

        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
